package com.kh.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kh.reggie.common.Result;
import com.kh.reggie.dto.DishDto;
import com.kh.reggie.entity.Category;
import com.kh.reggie.entity.Dish;
import com.kh.reggie.entity.DishFlavor;
import com.kh.reggie.entity.Employee;
import com.kh.reggie.service.CategoryService;
import com.kh.reggie.service.DishFlavorService;
import com.kh.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 菜品查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> page(int page, int pageSize, String name){
//        分页构造器
        Page<Dish> pageInfo = new Page(page,pageSize);
        Page<DishDto> dishDtoPage = new Page();
//        条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
//        添加过滤条件
        queryWrapper.like(StringUtils.isNotBlank(name),Dish::getName,name);
//        添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
//        执行查询
        dishService.page(pageInfo,queryWrapper);
//        对象拷贝,除了records以外的信息
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item)->{
            DishDto dishDto = new DishDto();
//            遍历拷贝records数据内容
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category!=null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());

//        List<DishDto> list = null;
        dishDtoPage.setRecords(list);

        return Result.success(dishDtoPage);
    }

    /**
     * 新增菜品
     * @param
     * @param dishDto
     * @return
     */
    @PostMapping
    public Result<String> save(@RequestBody DishDto dishDto){
        log.info("新增菜品:{}",dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        return Result.success("新增成功");
    }

    /**
     * 修改菜品信息的回显功能，填充到修改页面为修改菜品做准备
     * @param
     * @return
     */
    @GetMapping("/{id}")
    public Result<DishDto> get(@PathVariable Long id){

        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return Result.success(dishDto);
    }

    /**
     * 更新菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public Result<String> update(@RequestBody DishDto dishDto){
        log.info("修改菜品:{}",dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return Result.success("修改成功");
    }

    /**
     * 停售菜品:
     * @param ids
     * @return
     */
//    @PostMapping("/status/0")
//    public Result<String> statusChange0(@RequestParam Long ids ){
//        log.info("停售菜品:{}",ids);
//        Dish dish = dishService.getById(ids);
//        dish.setStatus(0);
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(Dish::getId,ids);
//
//        dishService.update(dish,queryWrapper);
//        return Result.success("停售成功");
//    }
    @PostMapping("/status/0")
    public Result<String> statusChange0(@RequestParam List<Long> ids ){
        log.info("停售几个菜品:{}__{}",ids.size(),ids);
        if (ids == null || ids.isEmpty()) {
            return Result.error("传入的ID列表为空");
        }
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId,ids).set(Dish::getStatus,0);

        boolean updated = dishService.update(null,updateWrapper);

        if (updated) {
            return Result.success("停售成功");
        } else {
            return Result.error("停售失败");
        }
    }
    /**
     * 起售菜品:
     * @param ids
     * @return
     */
//    @PostMapping("/status/1")
//    public Result<String> statusChange1(@RequestParam  Long ids ){
//        log.info("起售菜品:{}",ids);
//        Dish dish = dishService.getById(ids);
//        dish.setStatus(1);
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(Dish::getId,ids);
//
//        dishService.update(dish,queryWrapper);
//        return Result.success("起售成功");
//    }
    @PostMapping("/status/1")
    public Result<String> statusChange1(@RequestParam  List<Long> ids ){
        log.info("起售几个菜品:{}__{}",ids.size(),ids);
        if (ids == null || ids.isEmpty()) {
            return Result.error("传入的ID列表为空");
        }
        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId,ids).set(Dish::getStatus,1);

        boolean updated = dishService.update(null,updateWrapper);

        if (updated) {
            return Result.success("起售成功");
        } else {
            return Result.error("起售失败");
        }
    }
    /**
     * 这里是逻辑删除，不是真删，把isDeleted字段更新为1就不显示了，间接完成了逻辑删除
     * @param ids
     * @return
     */
//    @DeleteMapping
//    public Result<String> delete(@RequestParam  Long ids ){
//        log.info("删除菜品:{}",ids);
//        Dish dish = dishService.getById(ids);
//        dish.setIsDeleted(1);
//        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(Dish::getId,ids);
//
//        dishService.update(dish,queryWrapper);
//        return Result.success("删除成功");
//    }

//    /**
//     * 批量删除
//     * @param ids
//     * @return
//     */
//    @DeleteMapping
//    public Result<String> mDelete(@RequestParam  List<Long> ids ){
//        log.info("删除菜品几个{}",ids.size());
//        dishService.removeWithFlavor(ids);
//
//        return Result.success("删除成功");
//    }
    /**
     * 这里是批量逻辑删除，不是真删，把isDeleted字段更新为1就不显示了，间接完成了逻辑删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public Result<String> delete(@RequestParam  List<Long> ids ){
        log.info("删除菜品几个:{}",ids.size());
        //真正删除
//        dishService.removeWithFlavor(ids);

        if (ids == null || ids.isEmpty()) {
            return Result.error("传入的ID列表为空");
        }

        //判断是否在售，在Server层操作简单点，controller要写Mapper,这里不写了



        LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Dish::getId,ids).set(Dish::getIsDeleted,1);
        // 执行批量更新操作
        boolean updated = dishService.update(null, updateWrapper);

        if (updated) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }
    /**
     * 删除菜品信息(单个/批量)
     * @param
     * @return
     */
//    @DeleteMapping
//    public Result<String> delete(Long[] id) {
//        List<Long> list = Arrays.asList(id);
//
//        //删除菜品信息
//        dishService.removeByIds(Arrays.asList(id));
//
//        //删除对应dish_flavor中的信息
//        for (int i = 0; i < id.length; i++) {
//            DishFlavor dishFlavor = new DishFlavor();
//            dishFlavor.setDishId(id[i]);
//            QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>(dishFlavor);
//            dishFlavorService.remove(queryWrapper);
//        }
//
//        return Result.success("删除菜品信息成功");
//    }
    @GetMapping("/list")
    public Result<List<Dish>> list(Dish dish){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        return Result.success(list);
    }


}
